package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.encrypt.utils.EncryptUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.cloud.MiniCloudApi;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.SysMiniAdminBo;
import org.dromara.system.domain.bo.SysTenantBo;
import org.dromara.system.domain.vo.SysMiniAdminVo;
import org.dromara.system.mapper.*;
import org.dromara.system.service.ISysMiniAdminService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 小程序管理员Service业务层处理
 *
 * @author Michelle.Chung
 */
@RequiredArgsConstructor
@Service
public class SysMiniAdminServiceImpl implements ISysMiniAdminService {


    private final SysMiniAdminMapper baseMapper;

    @Resource
    MiniCloudApi miniCloudApi;

    /**
     * 查询小程序管理员
     */
    @Override
    public SysMiniAdminVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 基于租户ID查询小程序管理员
     */
    @Cacheable(cacheNames = CacheNames.SYS_MINI_ADMIN, key = "#tenantId")
    @Override
    public SysMiniAdminVo queryByTenantId(String tenantId) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<SysMiniAdmin>().eq(SysMiniAdmin::getTenantId, tenantId));
    }

    /**
     * 查询小程序管理员列表
     */
    @Override
    public TableDataInfo<SysMiniAdminVo> queryPageList(SysMiniAdminBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysMiniAdmin> lqw = buildQueryWrapper(bo);
        Page<SysMiniAdminVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询小程序管理员列表
     */
    @Override
    public List<SysMiniAdminVo> queryList(SysMiniAdminBo bo) {
        LambdaQueryWrapper<SysMiniAdmin> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysMiniAdmin> buildQueryWrapper(SysMiniAdminBo bo) {
        LambdaQueryWrapper<SysMiniAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTenantId()), SysMiniAdmin::getTenantId, bo.getTenantId());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), SysMiniAdmin::getUserName, bo.getUserName());
        lqw.orderByAsc(SysMiniAdmin::getId);
        return lqw;
    }

    /**
     * 新增小程序管理员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertByBo(SysMiniAdminBo bo) {
        SysMiniAdmin add = MapstructUtils.convert(bo, SysMiniAdmin.class);


        LambdaQueryWrapper<SysMiniAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(true, SysMiniAdmin::getUserName, bo.getUserName());


        SysMiniAdmin sysMiniAdminExist = baseMapper.selectOne(
            new LambdaQueryWrapper<SysMiniAdmin>().eq(SysMiniAdmin::getUserName, bo.getUserName()));
        if (ObjectUtil.isNotNull(sysMiniAdminExist)) {
            throw new ServiceException("该用户名已经存在");
        }

        add.setPassword(EncryptUtils.encryptByMd5(bo.getPassword()));
        int result =  baseMapper.insert(add);



        return result;
    }

    /**
     * 修改小程序管理员
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(SysMiniAdminBo bo) {
        SysMiniAdmin sysMiniAdmin = MapstructUtils.convert(bo, SysMiniAdmin.class);

        sysMiniAdmin.setPassword(EncryptUtils.encryptByMd5(bo.getPassword()));

        Boolean result = baseMapper.updateById(sysMiniAdmin) > 0;

        return result;
    }

    /**
     * 批量删除小程序管理员
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        Boolean result = baseMapper.deleteBatchIds(ids) > 0;

        return result;

    }

    /**
     * 校验用户名称是否唯一
     */
    @Override
    public boolean checkUserNameUnique(SysMiniAdminBo bo) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysMiniAdmin>()
            .eq(SysMiniAdmin::getUserName, bo.getUserName())
            .ne(ObjectUtil.isNotNull(bo.getTenantId()), SysMiniAdmin::getTenantId, bo.getTenantId()));
        return !exist;
    }
}
